<template>
  <div class="app-container">
    <div style="border: 1px gainsboro solid;padding: 10px 10px 10px 30px">
      <table border="0" >
        <tr>
          <td class="title">盘点任务：</td>
          <td class="content"><input type="text" v-model="this.form.planId" readonly @click="selectStockPlan" style="padding: 7px;border-radius: 5px;border: 1px gainsboro solid;width: 180px" placeholder=" 请选择盘点任务"/></td>
          <td class="title">预先盘点单：</td>
          <td class="content">
            <input type="text" v-model="this.form.preSheetId" readonly @click="selectPreSheet"
                   style="padding: 7px;border-radius: 5px;border: 1px gainsboro solid;width: 180px"
                   />
          </td>
          <td class="title">仓库：</td>
          <td class="content">{{ this.form.center.name }}</td>
        </tr>
        <tr>
          <td class="title">盘点类别：</td>
          <td class="content">{{ form.takeStockPlan.takeType==0 ? "全场盘点":form.takeStockPlan.takeType==1 ? "单品盘点":form.takeStockPlan.takeType==2 ? "类目盘点":form.takeStockPlan.takeType==3 ? "品牌盘点" : ""}}</td>
          <td class="title">盘点状态：</td>
          <td class="content">{{ form.takeStockPlan.takeStatus==0 ? "盘点任务生成":form.takeStockPlan.takeStatus==6 ? "盘点差异生成":form.takeStockPlan.takeStatus==9 ? "盘点完成" : form.takeStockPlan.takeStatus==12 ? "盘点已作废" : "" }}</td>
          <td class="title"><span v-if="form.takeStockPlan>1">类目/品牌：</span></td>
          <td class="content">{{ form.takeStockPlan.bizName }}</td>
        </tr>
        <tr>
          <td class="title">备注：</td>
          <td class="content" colspan="5"><el-input type="textarea" v-model="form.description" style="width: 700px;"/></td>
        </tr>
        <tr v-show="this.id!=null">
          <td class="title">状态：</td>
          <td class="content" colspan="5">{{ form.status === 0 ? "待审核" : form.status === 3 ? '审核通过' : '审核拒绝' }}</td>
        </tr>
        <tr v-show="this.id!=null">
          <td class="title">操作人：</td>
          <td class="content">{{form.createBy}}</td>
          <td class="title">操作时间：</td>
          <td class="content">{{form.createTime}}</td>
          <td class="title"></td>
          <td class="content"></td>
        </tr>
      </table>
    </div>
    <div style="border: 1px gainsboro solid;margin-top: 5px">
      <el-table height="400px" v-loading="loading" :data="this.tblTakeStockSheetDetailList">
        <el-table-column label="商品编号" align="left" prop="baseDataProduct.code" width="100px"/>
        <el-table-column label="商品名称" align="left" prop="baseDataProduct.name" width="200px">
          <template slot-scope="scope">
            <el-autocomplete
              class="inline-input"
              v-model="scope.row.baseDataProduct.name"
              placeholder="请输入内容"
              disabled
            >
              <template slot-scope="{ item }">
                <span>{{ item.name }}</span>
              </template>
            </el-autocomplete>
          </template>
        </el-table-column>
        <el-table-column label="单位" align="left" prop="baseDataProduct.unit" width="100px"/>
        <el-table-column label="规格" align="left" prop="baseDataProduct.spec" width="100px"/>
        <el-table-column label="商品类目" align="left" prop="baseDataProduct.baseDataProductCategory.name" width="100px"/>
        <el-table-column label="商品品牌" align="left" prop="baseDataProduct.baseDataProductBrand.name" width="100px"/>
        <el-table-column label="库存数量" align="left" prop="baseDataProduct.tblProductStock.stockNum" width="100px">
          <template slot-scope="scope">
            <span>{{  scope.row.baseDataProduct.tblProductStock.stockNum || 0}}</span>
          </template>
        </el-table-column>
        <el-table-column label="盘点数量" align="left" prop="takeNum" width="150">
          <template slot-scope="scope">
            <el-input type="text" v-model="scope.row.takeNum"/>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="left" prop="description" width="200">
          <template slot-scope="scope">
            <input type="text" v-model="scope.row.description" style="padding: 10px;border-radius: 5px;border: 1px gainsboro solid;width: 180px;">
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div slot="footer" class="dialog-footer" style="text-align: center;margin: 5px">
      <el-button type="primary" @click="submitForm(0)">确 定</el-button>
      <el-button type="success" @click="submitForm(3)" v-if="this.$route.query.id==null">审批通过</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>


    <!-- 获取盘点任务弹窗 -->
    <el-dialog title="盘点任务" :visible.sync="dialogFormVisible" width="1000px">
      <el-form :model="TakeStockQueryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="单号" prop="code">
          <el-input
            v-model="TakeStockQueryParams.code"
            placeholder="请输入单号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="仓库" prop="scId">
          <el-select v-model="TakeStockQueryParams.scId" @keyup.enter.native="handleQuery" clearable>
            <el-option v-for="storeCenter in StoreCenterInfoList" :key="storeCenter.id" :value="storeCenter.id" :label="storeCenter.name">{{storeCenter.name}}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="盘点状态" prop="takeStatus" label-width="150px">
          <el-select v-model="TakeStockQueryParams.takeStatus" clearable placeholder="全部" style="width: 100%">
            <el-option label="盘点任务生成" value="0" ></el-option>
            <el-option label="盘点差异生成" value="1" ></el-option>
            <el-option label="盘点完成" value="2" ></el-option>
            <el-option label="盘点已作废" value="3" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作时间" prop="updateTime">
          <el-date-picker clearable
                          v-model="TakeStockQueryParams.updateTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择操作时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="TakeStockPlanList" @row-click="handleRowClick">
        <el-table-column width="55" align="center">
          <template slot-scope="scope">
            <el-radio :label="scope.$index" v-model="selectedRowIndex" @change.native="handleRadioChange(scope.$index)"><span style="display: none">0</span></el-radio>
          </template>
        </el-table-column>
        <el-table-column label="单号" align="left" prop="code" width="200px"/>
        <el-table-column label="仓库编号" align="left" prop="center.code" width="100px"/>
        <el-table-column label="仓库名称" align="left" prop="center.name" width="100px"/>
        <el-table-column label="盘点类别" align="left" prop="takeType" width="100px" >
          <template slot-scope="scope">
            <span>{{ scope.row.takeType==0 ? "全场盘点":scope.row.takeType==1 ? "单品盘点":scope.row.takeType==2 ? "类目盘点":"品牌盘点" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="盘点状态" align="left" prop="takeStatus" width="150px" >
          <template slot-scope="scope">
            <span>{{ scope.row.takeStatus==0 ? "盘点任务生成":scope.row.takeStatus==6 ? "盘点差异生成":scope.row.takeStatus==9 ? "盘点完成":"盘点已作废" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="left" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作时间" align="left" prop="updateTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary"  @click="handleConfirm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 获取预先盘点弹窗 -->
    <el-dialog title="预先盘点单" :visible.sync="PreSheetOpen" width="1000px">
      <el-form :model="PreSheetQueryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="单号" prop="code">
          <el-input
            v-model="PreSheetQueryParams.code"
            placeholder="请输入单号"
            clearable
            @keyup.enter.native="PreSheetHandleQuery"
          />
        </el-form-item>
        <el-form-item label="盘点状态" prop="takeStatus" label-width="100px">
          <el-select v-model="PreSheetQueryParams.takeStatus" clearable placeholder="全部" style="width: 100%">
            <el-option label="初盘" value="0" ></el-option>
            <el-option label="复盘" value="1" ></el-option>
            <el-option label="抽盘" value="2" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作时间" prop="updateTime" label-width="100px">
          <el-date-picker clearable
                          v-model="PreSheetQueryParams.createTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择操作时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="PreSheetHandleQuery">搜索</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="PreSheetList" @row-click="PreSheetHandleRowClick">
        <el-table-column width="55" align="center">
          <template slot-scope="scope">
            <el-radio :label="scope.$index" v-model="PreSheetSelectedRowIndex" @change.native="PreSheetHandleRadioChange(scope.$index)"><span style="display: none">0</span></el-radio>
          </template>
        </el-table-column>
        <el-table-column label="单号" align="left" prop="code" width="350px"/>
        <el-table-column label="仓库编号" align="left" prop="center.code" width="100px"/>
        <el-table-column label="仓库名称" align="left" prop="center.name" width="100px"/>
        <el-table-column label="盘点状态" align="left" prop="takeStatus" width="150px" >
          <template slot-scope="scope">
            <span>{{ scope.row.takeStatus==0 ? "初盘":scope.row.takeStatus==1 ? "复盘":"抽盘" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作时间" align="left" prop="updateTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="PreSheetOpen = false">取 消</el-button>
        <el-button type="primary"  @click="PreSheetHandleConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {parseTime} from "../../../utils/ruoyi";
import { listReceiveSheet, getReceiveSheet, delReceiveSheet, addReceiveSheet, updateReceiveSheet,listByScId } from "@/api/system/ReceiveSheet";
import {listUser} from "@/api/system/erpUser";
import {listSupplier} from "@/api/system/Supplier";
import {listStoreCenterInfo} from "@/api/system/StoreCenterInfo";
import {listProductInfo} from "@/api/system/ProductInfo";
//商品库存
import { listStock} from "@/api/system/stock";
import {listPurchaseOrder} from "@/api/system/PurchaseOrder";
import productStock from "@/views/system/ProductStock/index.vue";
import {
  addTblTakeStockSheet,
  getTblTakeStockSheet,
  listTblTakeStockSheet,
  updateTblTakeStockSheet
} from "@/api/system/TblTakeStockSheet";
import {listTakeStockPlan} from "@/api/system/TakeStockPlan";
import {listProductCategory} from "@/api/system/ProductCategory";
import {listProductBrand} from "@/api/system/ProductBrand";
import {listSheet} from "@/api/system/PreTakeStockSheet";

export default {
  name: "orderAdd",
  data() {
    return {
      id: this.$route.query.id,

      //盘点任务ID框
      planId:null,
      // 任务查询参数
      TakeStockQueryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        scId: null,
        supplierId: null,
        purchaserId: null,
        createBy: null,
        createTime: null,
        approveBy: null,
        approveTime: null,
        status: 3,
      },
      //盘点任务数据
      TakeStockPlanList:[],
      selectedRowIndex: -1, // 选中的行索引
      selectedRowData: null, // 选中的行数据

      //预先盘点ID框
      PreSheetId:null,
      // 预先盘点查询参数
      PreSheetQueryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        scId: null,
        supplierId: null,
        purchaserId: null,
        createBy: null,
        createTime: null,
        approveBy: null,
        approveTime: null,
        status: 3,
      },
      //预先盘点数据
      PreSheetList:[],
      PreSheetSelectedRowIndex: -1, // 选中的行索引
      PreSheetSelectedRowData: null, // 选中的行数据

      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,


      //状态颜色
      statusColor:"rgb(100, 100, 100)",
      //用户列表
      UserList: [],
      //仓库列表
      StoreCenterInfoList: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scName: null,
        customerName: null,
      },

      // 表单参数
      form: {
        id:null,
        code:null,
        scId:null,
        description:"",
        createBy:null,
        createById:null,
        createTime:null,
        updateBy:null,
        updateById:null,
        updateTime:null,
        approveBy:null,
        approveTime:null,
        status:null,
        tblTakeStockSheetDetailList:[],
        center:{
          name:""
        },
        takeStockPlan:{
          takeType: null,
          takeStatus:null,
          bizName:''
        }
      },

      // 盘点单明细表格数据
      tblTakeStockSheetDetailList: [],
      // 盘点单表格数据
      TakeStockSheetList: [],
      //盘点单ID数据
      TakeStockSheetAllList:[],
      //盘点单详情表ID数据
      TakeStockSheetDetailAllList:[],
      // 商品库存表格数据
      productStock: [],

      //盘点任务弹窗
      dialogFormVisible: false,
      //预先盘点弹窗
      PreSheetOpen: false,

      //商品品牌/类目
      ids: [],
      brandList: [],
      categoryList: [],
    };
  },
  created() {
    //用户数据
    this.getUserList();
    //仓库数据
    this.getStoreCenterInfoList();
    //商品品牌/类目
    this.brandQuery();
    this.categoryQuery();

    //收货数据
    this.getTakeStockSheetAllList();
    if (this.$route.query.id!=null){
      this.selectTakeStockSheet();
    }
    this.loading = false;
  },
  methods: {
    parseTime,
    /** 查询盘点详情 */
    async selectTakeStockSheet() {
      const id = this.$route.query.id
      try {
        const response = await getTblTakeStockSheet(id);
        this.form = response.data;

        for (let i = 0; i < this.form.tblTakeStockSheetDetailList.length; i++) {
          const stock = await this.getProductStock(
            this.form.scId,
            this.form.tblTakeStockSheetDetailList[i].productId
          );

          if (stock) {
            this.form.tblTakeStockSheetDetailList[i].baseDataProduct.tblProductStock = stock;
          } else {
            this.form.tblTakeStockSheetDetailList[i].baseDataProduct.tblProductStock = {
              scId: this.form.scId,
              productId: this.form.tblTakeStockSheetDetailList[i].productId,
              stockNum: 0,
            };
          }
        }

        this.tblTakeStockSheetDetailList = this.form.tblTakeStockSheetDetailList;

        //获取盘点内容
        let ids=this.form.takeStockPlan.bizId.split(",");
        let name='';
        if (this.form.takeStockPlan.takeType===2){
          for (let k = 0; k < ids.length; k++) {
            for (let j = 0; j < this.categoryList.length; j++) {
              if (this.categoryList[j].id==ids[k]){
                name+=this.categoryList[j].name;
                if (k<ids.length-1)
                  name+='，';
              }
            }
          }
        }else if (this.form.takeStockPlan.takeType===3){
          for (let k = 0; k < ids.length; k++) {
            for (let j = 0; j < this.brandList.length; j++) {
              if (this.brandList[j].id==ids[k]){
                name+=this.brandList[j].name;
                if (k<ids.length-1)
                  name+='，';
              }
            }
          }
        }
        this.form.takeStockPlan.bizName=name;

        //状态值颜色判断
        if (response.data.status == 0){
          this.statusColor = "rgb(100, 100, 100)";
        }else if (response.data.status==3){
          this.statusColor = "rgb(82, 196, 26)";
        }else {
          this.statusColor = "rgb(255, 0, 0)";
        }

      } catch (error) {
        console.error('获取盘点任务列表失败:', error);
      } finally {
        this.loading = false;
      }
    },

    /** 查询用户列表 */
    getUserList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.UserList = response.rows;
      });
    },
    /** 查询仓库列表 */
    getStoreCenterInfoList() {
      this.loading = true;
      listStoreCenterInfo(this.queryParams).then(response => {
        this.StoreCenterInfoList = response.rows;
      });
    },


    //任务点击事件
    selectStockPlan() {
      this.dialogFormVisible=true;
      this.getStockPlanList();
    },

    //预先盘点点击事件
    selectPreSheet() {
      if (this.form.planId==null || this.form.planId==""){
        this.$modal.msgError("请选择先选择关联盘点任务");
        return false;
      }
      this.PreSheetOpen=true;
      this.getPreSheetList();
    },

    /** 盘带任务搜索按钮操作 */
    handleQuery() {
      this.TakeStockQueryParams.pageNum = 1;
      this.getStockPlanList();
    },
    /** 预先盘点搜索按钮操作 */
    PreSheetHandleQuery() {
      this.TakeStockQueryParams.pageNum = 1;
      this.getPreSheetList();
    },
    /** 查询盘点任务列表 */
    async getStockPlanList() {
      this.loading = true;
      this.TakeStockPlanList = [];

      try {
        const response = await listTakeStockPlan(this.TakeStockQueryParams);
        this.TakeStockPlanList = response.rows;

        for (let i = 0; i < this.TakeStockPlanList.length; i++) {
          for (let j = 0; j < this.TakeStockPlanList[i].tblTakeStockPlanDetailList.length; j++) {
            const stock = await this.getProductStock(
              this.TakeStockPlanList[i].scId,
              this.TakeStockPlanList[i].tblTakeStockPlanDetailList[j].productId
            );

            if (stock) {
              this.TakeStockPlanList[i].tblTakeStockPlanDetailList[j].baseDataProduct.tblProductStock = stock;
            } else {
              this.TakeStockPlanList[i].tblTakeStockPlanDetailList[j].baseDataProduct.tblProductStock = {
                scId: this.TakeStockPlanList[i].scId,
                productId: this.TakeStockPlanList[i].tblTakeStockPlanDetailList[j].productId,
                stockNum: 0,
                taxPrice: this.TakeStockPlanList[i].tblTakeStockPlanDetailList[j].taxPrice,
                taxAmount: 0,
              };
            }
          }

          //获取盘点内容
          if (this.TakeStockPlanList.takeType>1){
            let ids=this.TakeStockPlanList[i].bizId.split(",");
            let name='';
            if (this.TakeStockPlanList[i].takeType==2){
              for (let k = 0; k < ids.length; k++) {
                for (let j = 0; j < this.categoryList.length; j++) {
                  if (this.categoryList[j].id==ids[k]){
                    name+=this.categoryList[j].name;
                    if (k<ids.length-1)
                      name+='，';
                  }
                }
              }
            }else if (this.TakeStockPlanList.takeType==3){
              for (let k = 0; k < ids.length; k++) {
                for (let j = 0; j < this.brandList.length; j++) {
                  if (this.brandList[j].id==ids[k]){
                    name+=this.brandList[j].name;
                    if (k<ids.length-1)
                      name+='，';
                  }
                }
              }
            }
            this.TakeStockPlanList[i].bizName=name;
          }

        }
      } catch (error) {
        console.error('获取盘点任务列表失败:', error);
      } finally {
        this.loading = false;
      }
    },

    /** 查询预先盘点列表 */
    getPreSheetList() {
      this.loading = true;
      this.PreSheetList = [];
      this.PreSheetQueryParams.scId=this.form.scId

      listSheet(this.PreSheetQueryParams).then(response => {
        this.PreSheetList = response.rows;
        this.loading = false;
      });
    },


    handleRowClick(row, column, event) {
      this.selectedRowIndex = this.TakeStockPlanList.indexOf(row);
      this.selectedRowData = row; // 更新选中的行数据
    },
    handleRadioChange(index) {
      this.selectedRowIndex = index;
      // 清除其他行的选中状态
      this.$refs.singleTable.clearCurrentRow();
      this.$refs.singleTable.setCurrentRow(this.TakeStockPlanList[index]);
      this.selectedRowData = this.TakeStockPlanList[index]; // 更新选中的行数据
    },
    handleConfirm() {
      if (this.selectedRowData) {
        // 将选中的行数据传递给父组件
        this.$emit('order-selected', this.selectedRowData);
      }
      this.planId=this.selectedRowData.id;
      this.form.planId=this.selectedRowData.id;
      this.form.scId=this.selectedRowData.scId;
      this.form.takeStockPlan=this.selectedRowData;
      this.form.center=this.selectedRowData.center;

      this.tblTakeStockSheetDetailList=[]
      for (let i = 0; i < this.selectedRowData.tblTakeStockPlanDetailList.length; i++) {
        var receiveSheet={}
        receiveSheet.id=generateUniqueId(this.TakeStockSheetDetailAllList)
        receiveSheet.sheetId=this.form.id
        receiveSheet.productId=this.selectedRowData.tblTakeStockPlanDetailList[i].productId

        if (this.selectedRowData.tblTakeStockPlanDetailList[i].takeNum!=null){
          receiveSheet.takeNum=this.selectedRowData.tblTakeStockPlanDetailList[i].takeNum
        }else {
          receiveSheet.takeNum=this.selectedRowData.tblTakeStockPlanDetailList[i].oriTakeNum||0
        }

        receiveSheet.orderNo=i+1;
        receiveSheet.baseDataProduct=this.selectedRowData.tblTakeStockPlanDetailList[i].baseDataProduct;
        this.tblTakeStockSheetDetailList.push(receiveSheet);
      }

      this.dialogFormVisible = false; // 关闭弹窗

    },

    //预先盘点点击事件
    PreSheetHandleRowClick(row, column, event) {
      this.PreSheetSelectedRowIndex = this.PreSheetList.indexOf(row);
      this.PreSheetSelectedRowData = row; // 更新选中的行数据
    },
    PreSheetHandleRadioChange(index) {
      this.PreSheetSelectedRowIndex = index;
      // 清除其他行的选中状态
      this.$refs.singleTable.clearCurrentRow();
      this.$refs.singleTable.setCurrentRow(this.PreSheetList[index]);
      this.PreSheetSelectedRowData = this.PreSheetList[index]; // 更新选中的行数据
    },
    PreSheetHandleConfirm() {
      if (this.PreSheetSelectedRowData) {
        // 将选中的行数据传递给父组件
        this.$emit('order-selected', this.PreSheetSelectedRowData);
      }

      for (let i = 0; i < this.tblTakeStockSheetDetailList.length; i++) {
        this.tblTakeStockSheetDetailList[i].takeNum=0;
      }

      this.form.preSheetId=this.PreSheetSelectedRowData.id;

      let scId=this.PreSheetSelectedRowData.scId;
      for (let j = 0; j < this.PreSheetSelectedRowData.tblPreTakeStockSheetDetailList.length; j++) {
        let productId=this.PreSheetSelectedRowData.tblPreTakeStockSheetDetailList[j].productId;

        for (let i = 0; i < this.tblTakeStockSheetDetailList.length; i++) {
          if(this.form.scId==scId && this.tblTakeStockSheetDetailList[i].baseDataProduct.id==productId){
            this.tblTakeStockSheetDetailList[i].takeNum=this.PreSheetSelectedRowData.tblPreTakeStockSheetDetailList[j].firstNum
            if (this.PreSheetSelectedRowData.secondNum!=null){
              this.tblTakeStockSheetDetailList[i].takeNum=this.PreSheetSelectedRowData.tblPreTakeStockSheetDetailList[j].secondNum
            }
            if (this.PreSheetSelectedRowData.randNum!=null){
              this.tblTakeStockSheetDetailList[i].takeNum=this.PreSheetSelectedRowData.tblPreTakeStockSheetDetailList[j].randNum
            }
          }
        }
      }

      this.PreSheetOpen = false; // 关闭弹窗
    },



    //商品库存
    async getProductStock(scId, productId) {
      try {
        const response = await listStock({ scId, productId });
        const stock = response.rows[0];
        return stock;
      }catch (error) {
        console.error('获取商品库存失败:', error);
        return null; // 返回 null 表示获取失败
      }
    },

    // 取消按钮
    cancel() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.back();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        available: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null
      };
      this.resetForm("form");
    },

    /** 提交按钮 */
    submitForm(status) {
      if(this.formInfo()){
        if (this.form.id != null) {
          console.log(this.form)
          updateTblTakeStockSheet(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.back();
          });
        } else {
          const newId = generateUniqueId(this.TakeStockSheetAllList);
          var code = getOrderCode(this.TakeStockSheetList);
          this.form.id=newId;
          this.form.code=code;
          for (var i = 0; i < this.tblTakeStockSheetDetailList; i++) {
            this.tblTakeStockSheetDetailList[i].sheetId=newId;
          }
          this.form.tblTakeStockSheetDetailList=this.tblTakeStockSheetDetailList;
          this.form.createBy="系统管理员";
          this.form.createById="1";
          this.form.updateBy="系统管理员";
          this.form.updateById="1";
          this.form.status=status;
          if (status===3 ){
            this.form.approveBy='1';
            this.form.approveTime=new Date();
          }

          addTblTakeStockSheet(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.back();
          });
        }
      }
    },
    //提交表单验证
    formInfo(){
      if (this.form.planId==null){
        this.$modal.msgError("请选择关联盘点任务");
        return false;
      }
      if (this.form.scId==null){
        this.$modal.msgError("请选择仓库");
        return false;
      }

      for (var i = 0; i < this.tblTakeStockSheetDetailList.length; i++) {
        if (this.tblTakeStockSheetDetailList[i].takeNum==null){
          this.$modal.msgError(this.tblTakeStockSheetDetailList[i].baseDataProduct.name+"的盘点数量为空");
          return false;
        }
      }

      return true;
    },


    // 获取所有盘点单详情数据ID
    getTakeStockSheetAllList(){
      this.TakeStockSheetList=[];
      this.TakeStockSheetAllList=[];
      this.TakeStockSheetDetailAllList=[];

      listTblTakeStockSheet({}).then(response => {
          this.TakeStockSheetList=response.rows;

          for (var i=0;i<this.TakeStockSheetList.length;i++){
            this.TakeStockSheetAllList.push(this.TakeStockSheetList[i].id);
            for (var j=0;j<this.TakeStockSheetList[i].tblTakeStockSheetDetailList.length;j++){
              this.TakeStockSheetDetailAllList.push(this.TakeStockSheetList[i].tblTakeStockSheetDetailList[j].id);
            }
          }
      });
    },

    //商品类目
    categoryQuery(){
      this.categoryList=[]
      listProductCategory({}).then(response => {
        this.categoryList = response.rows;
      });
    },
    //商品品牌
    brandQuery(){
      this.brandList=[]
      listProductBrand({}).then(response => {
        this.brandList = response.rows;
      });
    },
  },
  beforeRouteLeave(to, from, next) {
    // 设置一个标志，表示需要刷新数据
    to.meta.refresh = true;
    next();
  }
};

// ID生成
function generateUniqueId(existingIds) {
  const prefix = '18';
  const length = 19 - prefix.length;
  const characters = '0123456789';
  let uniqueId;

  do {
    uniqueId = prefix;
    for (let i = 0; i < length; i++) {
      uniqueId += characters.charAt(Math.floor(Math.random() * characters.length));
    }
  } while (existingIds.includes(uniqueId));

  return uniqueId;
}

//单号生成
function getOrderCode(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="PDGL";    //盘点管理
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,)
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}
</script>
<style>
  .title{
    width: 150px;
    height: 50px;
    text-align: right;
  }
  .content{
    width: 200px;
    height: 50px;
  }
</style>
